<?php
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2020 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------
namespace app\controller\api\store;

use app\model\order\StoreOrder;
use app\model\order\StoreOrderCartInfo;
use app\Request;
use app\services\activity\collage\UserCollageCodeServices;
use app\services\order\store\BranchOrderServices;
use app\services\order\StoreOrderCartInfoServices;
use app\services\order\StoreOrderDeliveryServices;
use app\services\order\StoreOrderEconomizeServices;
use app\services\order\StoreOrderPromotionsServices;
use app\services\order\StoreOrderRefundServices;
use app\services\order\StoreOrderServices;
use app\services\order\StoreOrderWapServices;
use app\services\store\DeliveryServiceServices;
use app\services\store\SystemStoreServices;
use app\services\store\SystemStoreStaffServices;
use app\services\user\UserServices;
use think\facade\Db;
use think\exception\ValidateException;

use function AlibabaCloud\Client\value;


/**
 * 配送员
 * Class StoreDelivery
 * @package app\controller\store\staff
 */
class StoreDelivery
{
    /**
     * @var DeliveryServiceServices
     */
    protected $services;

    /**
     * StoreDelivery constructor.
     * @param DeliveryServiceServices $services
     */
    public function __construct(DeliveryServiceServices $services)
    {
        $this->services = $services;
    }

    /**
     * 获取配送员信息
     * @param Request $request
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function info(Request $request, SystemStoreServices $storeServices, UserServices $userServices)
    {
        $uid = (int)$request->uid();
        $deliveryInfo = $this->services->getDeliveryInfoByUid($uid)->toArray();
        $store_ids = $this->services->getDeliveryStoreIds($uid, 1,'relation_id');
        $store_info = [];
        if ($store_ids) {
            $store_info = $storeServices->getColumn([['id', 'in', $store_ids], ['is_show', '=', 1], ['is_del', '=', 0]], 'id,name');
        }
        $deliveryInfo['store_info'] = $store_info;
        $deliveryInfo['user_nickname'] = $userServices->value(['uid' => $uid], 'nickname');
        return app('json')->success($deliveryInfo);
    }

    /**
     * 获取所有配送员列表
     * @param DeliveryServiceServices $services
     * @return mixed
     */
    public function getDeliveryAll(Request $request, SystemStoreStaffServices $staffServices)
    {
        $uid = (int)$request->uid();
        $staffInfo = $staffServices->getStaffInfoByUid($uid);
        $list = $this->services->getDeliveryList(1, (int)$staffInfo['store_id']);
        return app('json')->success($list['list']);
    }

    /**
     * 配送员数据统计
     * @param Request $request
     * @return mixed
     */
    public function statistics(Request $request)
    {
        [$store_id, $time] = $request->getMore([
            ['store_id', 0],
            ['data', '', '', 'time'],
        ], true);
        $uid = (int)$request->uid();
        $data = $this->services->getStoreData($uid, $store_id, $time);
        return app('json')->successful($data);
    }

    /**
     * 配送统计列表数据
     * @param Request $request
     * @return mixed
     */
    public function data(Request $request, BranchOrderServices $orderServices)
    {
        [$store_id, $time] = $request->getMore([
            ['store_id', 0],
            ['data', '', '', 'time'],
        ], true);
        $uid = (int)$request->uid();
        $this->services->getDeliveryInfoByUid($uid, $store_id ? 1: 0, (int)$store_id);
        $where = ['delivery_uid' => $uid, 'time' => $time];
        if ($store_id) {
            $where['store_id'] = $store_id;
        }
        $data = $orderServices->getOrderDataPriceCount($where);
        return app('json')->successful($data);
    }




    public function orderList(Request $request, BranchOrderServices $orderServices)
    {
        [$type] = $request->getMore([
            ['type', 1]
        ], true);
        $uid = (int)$request->uid();
        $where = ['delivery_uid' => $uid, 'status' => 9, 'is_del' => 0, 'is_system_del' => 0, 'paid' => 1, 'refund_status' => [0, 3]];
        if ($type == 1) {
            $where['status'] = 2;
        }
        $list = $orderServices->getStoreOrderList($where, ['*'], ['pink', 'store' => function ($query) {
            $query->field('id,name,address,detailed_address');
        }]);
        $data = [];
        $where['status'] = 2;
        $data['unsend'] = $orderServices->count($where);
        $where['status'] = 9;
        $data['send'] = $orderServices->count($where);
        return app('json')->successful(compact('data', 'list'));
    }

	/**
	 * 配送订单列表记录
	 * @param Request $request
	 * @return mixed
	 */
	public function orderList_jilu(Request $request, BranchOrderServices $orderServices)
	{
		$uid = (int)$request->uid();

		$where = ['delivery_uid' => $uid, 'status' => 12, 'is_del' => 0, 'is_system_del' => 0, 'paid' => 1];

		$list = $orderServices->getStoreOrderList3($where, ['*'],['pink', 'store' => function ($query) {
			$query->field('id,name,address,detailed_address');
		}]);

		return app('json')->successful(compact( 'list'));
	}


	/**
	 * 配送未结单订单合计
	 * @param Request $request
	 * @return mixed
	 */
	public function order_no_count(Request $request, BranchOrderServices $orderServices)
	{
		$uid = (int)$request->uid();

		[$cat] = $request->getMore([
			['cat','']
		], true);
        if ($cat==2){
            $uid=$uid;
        }else{
            $uid=[0,$uid];
        }

		$data=Db::name('user_ship_address')->where ('pid', 0)->field ('id,name,station_type')->order ('sort','aoc')->select();
		$datas=[];
		foreach ($data as $k=>&$v) {
			$address = Db::name('user_ship_address')->where ('pid',$v['id'])->field ('id,name,station_type')->order ('sort','aoc')->select();
			$count =0;

			foreach ($address as $k2 => &$v2) {
				$addresss = Db::name('user_ship_address')->where ('pid',$v2['id'])->order ('sort','aoc')->field ('id,name,station_type')->select();
				foreach ($addresss as $k1 => &$v1) {
//					$addressss = Db::name('user_ship_address')->where ('pid',$v1['id'])->order ('sort','aoc')->field ('id,name,station_type')->select();
//					foreach ($addressss as $k22 => &$vv) {
						$where = ['unit_id' => $v1['id'],'status' => 10,'is_system_del' => 0, 'cat' => $cat,'delivery_uid'=>$uid];

                    $v1['count'] = $orderServices->getcount2($where);
//					}
					$v2['data'][]=$v1;
				}
				$where = ['address_location' => $v2['id'],'status' => 101,'is_system_del' => 0, 'cat' => $cat,'delivery_uid'=>$uid];
				$count+=$v2['count'] = $orderServices->getcount2($where);
				$v['data'][]=$v2;
			}


			$v['count']=$count;
			$datas[]=$v;
		}
		return app('json')->successful($datas);
	}

	public function is_peisongyuan(Request $request)
	{
		$uid = (int)$request->uid();
		/** @var DeliveryServiceServices $deliveryService */
		$deliveryService = app()->make(DeliveryServiceServices::class);
		$deliveryUser3 = $deliveryService->checkoutIs3Service($uid); // 检查用户是否是配送员
		$deliveryUser4 = $deliveryService->checkoutIs4Service($uid); // 检查用户是否是配送员
		$deliveryUser5 = $deliveryService->checkoutIs5Service($uid); // 检查用户是否是配送员
		$deliveryUser1 = $deliveryService->checkoutIs6Service($uid); // 检查用户是否是配送员

		$data = Db::name('surveyor_service')->where('uid',$uid)->where ('status',1)->where ('is_del',0)->count();

		$repair_service = Db::name('repair_service')->where('uid',$uid)->where ('status',1)->where ('is_del',0)->count();

		$status['delivery_status6']=0;
		$status['delivery_status3']=0;
		$status['delivery_status4']=0;
		$status['delivery_status5']=0;
		$status['surveyor_status']=0;
		$status['repair_status']=0;

		if ($deliveryUser1)		$status['delivery_status6']=1;
		if ($deliveryUser3)		$status['delivery_status3']=1;
		if ($deliveryUser4)		$status['delivery_status4']=1;
		if ($deliveryUser5)		$status['delivery_status5']=1;
		if ($data)		        $status['surveyor_status']=1;
		if ($repair_service)	$status['repair_status']=1;
		return app('json')->successful($status);
	}

	/**
	 * 配送完成
	 * @param Request $request
	 * @return mixed
	 */
	public function order_distribution(Request $request)
	{
		[$order_id,$authority_confirm_img,$confirm_kt_img,$replenishment,$refund_img,$refund_water,$my_kt_img,$huitong,$authority_remark,$songsui_count,$tui_count]= $request->postMore([
			['order_id',''],
			['authority_confirm_img',''],
			['confirm_kt_img',''],
			['replenishment',0],///补桶
			['refund_img',''],//退水照片
			['refund_water',0],//退水数量
			['my_kt_img',''],//自有张照片
			['huitong',0], //拿回来多少桶
			['authority_remark',''],//  备注
			['songsui_count',0],//送水数量
			['tui_count',0],//
		], true);
		$data['authority_confirm_img'] = $authority_confirm_img;
		$data['confirm_kt_img'] = $confirm_kt_img;
		$data['replenishment'] = $replenishment;
		$data['refund_img'] = $refund_img;
		$data['refund_water'] = $refund_water;
		$data['my_kt_img'] = $my_kt_img;
		$data['authority_remark'] = $authority_remark;
		$data['songsui_count'] = $songsui_count;
		$data['huitong'] = $huitong;
		$data['tui_count'] = $tui_count;
		if(empty($order_id)){
			return app('json')->fail ('订单不能为空');
		}
		$data=$this->services->order_take_goods($order_id,$data);
		if ($data['status']){
			return app('json')->successful('配送完成',$data);
		}else{
			return app('json')->fail($data['msg']);

		}
	}

	//送水工 退回水票
	public function refund_water ()
	{

		$refund_water_number = input ('refund_water_number');
		$order_id = input ('order_id');

		if (empty($refund_water_number)) {
			$return_data = array (
				'status' => false,
				'msg' => '退回数量不能为空',
			);
			return app('json')->fail('退回数量不能为空');
		}
		if (empty($order_id)) {
			$return_data = array (
				'status' => false,
				'msg' => 'order_id不能为空',
			);
			return json_encode ($return_data);
		}
		$water_tickets = Db ::name ('water_ticket') -> where ('order_sn', $order_id) -> find ();

		$ticket = Db ::name ('water_ticket')
			-> where ('goods_id', $water_tickets[ 'goods_id' ])
			-> where ('user_id', $water_tickets[ 'user_id' ])
			-> order ('id desc')
			-> find ();

		$num = 0;
		if ($ticket) {
			$num = $ticket[ 'num' ] + $refund_water_number;
		}
		$water_ticket[ 'order_sn' ] = $order_id;
		$water_ticket[ 'user_id' ] = $ticket[ 'user_id' ];
		$water_ticket[ 'goods_id' ] = $ticket[ 'goods_id' ];
		$water_ticket[ 'type' ] = 1;
		$water_ticket[ 'nums' ] = $refund_water_number;
		$water_ticket[ 'goods_name' ] = $ticket['goods_name'];
		$water_ticket[ 'createtime' ] = time ();
		$water_ticket[ 'num' ] = $num;
		$water_ticket[ 'remark' ] = '退回水票' . $refund_water_number . "张";
		Db ::name ('water_ticket') -> insert ($water_ticket);
		return app('json')->successful('ok');
	}

	//工人绩效
	public function worker_user_info(Request $request)
	{
		$time = input('time');
		if (!$time){
			$time = \date('Y-m');
		}
		$uid = (int)$request->uid();
		$data['res'] = Db::name('worker_examine')->where('user_id',$uid)->where('time', $time)
			->field('sum(single_quantity) as single_quantity,sum(performance) as performance, sum(Bad) as Bad,sum(esteem)  as esteem ,sum(substract)  as substract ,sum(settlement)  as settlement,sum(ticheng)  as ticheng ,time')
			->find();

		$data['res']['single_quantity']= $data['res']['single_quantity']==null?0:$data['res']['single_quantity'];
		$data['res']['performance']=$data['res']['performance']==null?0:$data['res']['performance'];
		$data['res']['Bad']=$data['res']['Bad']==null?0:$data['res']['Bad'];
		$data['res']['esteem']=$data['res']['esteem']==null?0:$data['res']['esteem'];
		$data['res']['substract']=$data['res']['substract']==null?0:$data['res']['substract'];
		$data['res']['settlement']=$data['res']['settlement']==null?0:$data['res']['settlement'];
		$data['res']['ticheng']=$data['res']['ticheng']==null?0:$data['res']['ticheng'];
		$data['res']['time']=$data['res']['time']==null?0:$data['res']['time'];

		return app('json')->successful($data);

	}

	//查询员工每天订单绩效查询
	public function select_work(Request $request){
		$uid = (int)$request->uid();
		$time=input('time');

		if (empty($time)){
			$time = date('Y-m');

		}
		$data =Db::name('worker_examine')
			->alias ('o')
			->where('o.time',$time)
			->where('o.user_id',$uid)
			->field('o.*')
			->order ('times','desc')
			->select()
			->toArray();

		return app('json')->successful('ok',$data);
	}

	/**
	 * 核验自有空桶数量
	 * @param Request $request
	 * @return mixed
	 */
	public function order_ziyou_heyan(Request $request){
		[$order_id,$uid,$nums]= $request->postMore([
			['order_id',''],
			['uid',''],
			['nums',0],
		], true);
		Db::name('water_user_kt_list')->where ('order_id',$order_id)->update (['nums'=>$nums,'is_status'=>1]);
		Db::name('water_user')->where ('uid',$uid)->update (['my_kt_ktpledge'=>$nums]);
		return app('json')->successful('ok');

	}

	/**
	 * 获取配送员信息
	 * @param Request $request
	 * @return mixed
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\DbException
	 * @throws \think\db\exception\ModelNotFoundException
	 */
	public function get_user_info(Request $request,SystemStoreServices $storeServices, UserServices $userServices)
	{
		$uid = input ('id');
		$deliveryInfo = $this->services->getDeliveryInfoByUid($uid)->toArray();
		$store_ids = $this->services->getDeliveryStoreIds($uid, 1,'relation_id');
		$store_info = [];
		if ($store_ids) {
			$store_info = $storeServices->getColumn([['id', 'in', $store_ids], ['is_show', '=', 1], ['is_del', '=', 0]], 'id,name');
		}
		$deliveryInfo['store_info'] = $store_info;
		$deliveryInfo['user_nickname'] = $userServices->value(['uid' => $uid], 'nickname');
		return app('json')->success($deliveryInfo);
	}
	public function add_user_comment (Request $request , StoreOrder $StoreOrder)
	{
		[$order_id,$content,$status]= $request->postMore([
			['order_id', ''],//订单状态
			['content', ''],//订单状态
			['status', ''],//订单状态
		], true);
		$StoreOrder->where('order_id',$order_id)->update(['content'=> $content,'comment_time'=>time(),'comment_status'=>$status]);
		$user =Db::name('worker_examine')->where('order_id',$order_id)->find();
        Db::name('worker_examine')->where('order_id',$order_id)->where('Bad','>',0)->delete();
		if ($status==2){
			$date = date('Y-m');
			$dates = date('Y-m-d H:i:s');
			$dated = date('Y-m-d ');
			Db::name('worker_examine')->insert(['time'=>$date,
				'user_id'=> $user['user_id'],
				'single_quantity'=>0,
				'performance'=>0,
				'Bad'=>1,
				'esteem'=>0,
				'substract'=>10,
				'ticheng'=>0,'times'=>$dates,'timed'=>$dated,'order_id'=>$order_id]);
		}

		return app('json')->success('ok');

	}
	//打包员=================================================== 打包员
	//未打包的订单
    public function order_no_packing(Request $request,BranchOrderServices $orderServices){
        [$status] = $request->getMore([
            ['status',111],
//            ['unit_id',0],
//            ['address_location',0],
        ], true);
        $uid = (int)$request->uid();
        $where = ['status' => $status, 'is_del' => 0,'is_system_del' => 0,'delivery_uid'=>[0, $uid]];
        $list = $orderServices->getStoreOrderList2($where, ['*'], ['pink', 'store' => function ($query) {
            $query->field('id,name,address,detailed_address');
        }]);

        $data = [];
        return app('json')->successful($list);

    }
    /**
     * 添加打包订单
     * @param Request $request
     * @return mixed
     */
    public function order_add_packing(Request $request, StoreOrder $orderServices){
        [$order_id] = $request->getMore([
            ['order_id',''],
        ], true);
        /** @var StoreOrder $StoreOrder */
        $StoreOrder = app()->make(StoreOrder::class);
        $where['order_id'] = ['eq', $order_id];
        $info = $StoreOrder->where($where)->find()->toArray ();
        /** @var StoreOrderRefundServices $storeOrderRefundServices */
        $storeOrderRefundServices = app()->make(StoreOrderRefundServices::class);
        if ($storeOrderRefundServices->count(['store_order_id' => $info['id'], 'refund_type' => [0, 1, 2, 4, 5, 6], 'is_cancel' => 0, 'is_del' => 0])) {
            return app('json')->fail('订单有售后申请请先处理',['code'=>40001]);
        }
        if ($info['pid'] == -1) return app('json')->fail('订单已被拆分为多个订单，请刷新列表数据',['code'=>40001]);
        $status =$orderServices->where('order_id',$order_id)->value ('status1');
        if ($status==2.0){
            $orderServices->where('order_id',$order_id)->where('cashier_uid',0)->update(['status1'=>2.5,'cashier_uid'=>$request->uid ()]);
        }elseif ($status==1.0){
            $orderServices->where('order_id',$order_id)->where('distributor_uid',0)->update(['status1'=>1.5,'distributor_uid'=>$request->uid ()]);
        }

        return app('json')->success('操作完成');
    }
    /**
     * 打包完成操作
     * @param Request $request
     * @return mixed
     */
    public function order_packing_ok(Request $request, StoreOrder $orderServices){
        [$order_id] = $request->getMore([
            ['order_id',''],
        ], true);
        $name=DB::name('delivery_service')->where('uid','in',$request->uid())->value('nickname');
        /** @var StoreOrder $StoreOrder */
        $StoreOrder = app()->make(StoreOrder::class);
        $where['order_id'] = ['eq', $order_id];
        $info = $StoreOrder->where($where)->find()->toArray ();
        /** @var StoreOrderRefundServices $storeOrderRefundServices */
        $storeOrderRefundServices = app()->make(StoreOrderRefundServices::class);
        if ($storeOrderRefundServices->count(['store_order_id' => $info['id'], 'refund_type' => [0, 1, 2, 4, 5, 6], 'is_cancel' => 0, 'is_del' => 0])) {
            return app('json')->fail('订单有售后申请请先处理',['code'=>40001]);

        }
        if ($info['pid'] == -1) return app('json')->fail('订单已被拆分为多个订单，请刷新列表数据',['code'=>40001]);

        $uid = (int)$request->uid();
        $status =$orderServices->where('order_id',$order_id)->value ('status1');
        if ($status==1.5){
            $orderServices->where('order_id',$order_id)->where('distributor_uid',$request->uid ())->update(['status1'=>2,'distributor_name'=>$name,'distributor_time'=>date('Y-m-d H:i:s')]);

        }elseif ($status==2.5){
            $orderServices->where('order_id',$order_id)->where('cashier_uid',$request->uid ())->update(['status1'=>3,'cashier_name'=>$name,'cashier_uid'=>$request->uid (),'cashier_time'=>date('Y-m-d H:i:s')]);
        }
        return app('json')->success('操作完成');
    }

//水站的打包员===============================================水站的打包员
    public function order_no_packing1(Request $request,BranchOrderServices $orderServices){
        [$status] = $request->getMore([
            ['status',1111],
        ], true);
        $uid = (int)$request->uid();
        $where = ['status' => $status, 'is_del' => 0,'is_system_del' => 0,'delivery_uid'=>[0, $uid]];
        $list = $orderServices->getStoreOrderList2($where, ['*'], ['pink', 'store' => function ($query) {
            $query->field('id,name,address,detailed_address');
        }]);

        $data = [];
        return app('json')->successful($list);

    }
    public function order_no_shuizhan_packing_count(Request $request,BranchOrderServices $orderServices){
        [$status] = $request->getMore([
            ['status',1111],
        ], true);
        $uid = (int)$request->uid();
        $where = ['status' => $status, 'is_del' => 0,'is_system_del' => 0,'delivery_uid'=>[0, $uid]];
        $count =  $orderServices->getcount2($where);

        $data = [];
        return app('json')->successful($count);

    }
    /**
     * 添加打包订单
     * @param Request $request
     * @return mixed
     */
    public function order_add_packing1(Request $request, StoreOrder $orderServices){
        [$order_id] = $request->getMore([
            ['order_id',''],
        ], true);
        /** @var StoreOrder $StoreOrder */
        $StoreOrder = app()->make(StoreOrder::class);
        $where['order_id'] = ['eq', $order_id];
        $info = $StoreOrder->where($where)->find()->toArray ();
        /** @var StoreOrderRefundServices $storeOrderRefundServices */
        $storeOrderRefundServices = app()->make(StoreOrderRefundServices::class);
        if ($storeOrderRefundServices->count(['store_order_id' => $info['id'], 'refund_type' => [0, 1, 2, 4, 5, 6], 'is_cancel' => 0, 'is_del' => 0])) {
            return app('json')->fail('订单有售后申请请先处理',['code'=>40001]);
        }
        if ($info['pid'] == -1) return app('json')->fail('订单已被拆分为多个订单，请刷新列表数据',['code'=>40001]);
        if ($info['refund_status'] == 1||$info['refund_status'] == 2) return app('json')->fail('请刷新列表数据',['code'=>40001]);
        $status =$orderServices->where('order_id',$order_id)->value ('status1');
        if ($status==2.0){
            $orderServices->where('order_id',$order_id)->where('cashier_uid',0)->update(['status1'=>2.5,'cashier_uid'=>$request->uid ()]);
        }elseif ($status==1.0){
            $orderServices->where('order_id',$order_id)->where('distributor_uid',0)->update(['status1'=>1.5,'distributor_uid'=>$request->uid ()]);
        }

        return app('json')->success('操作完成');
    }
    /**
     * 打包完成操作
     * @param Request $request
     * @return mixed
     */
    public function order_packing_ok1(Request $request, StoreOrder $orderServices){
        [$order_id] = $request->getMore([
            ['order_id',''],
        ], true);
        $name=DB::name('delivery_service')->where('uid','in',$request->uid())->value('nickname');
        /** @var StoreOrder $StoreOrder */
        $StoreOrder = app()->make(StoreOrder::class);
        $where['order_id'] = ['eq', $order_id];
        $info = $StoreOrder->where($where)->find()->toArray ();
        /** @var StoreOrderRefundServices $storeOrderRefundServices */
        $storeOrderRefundServices = app()->make(StoreOrderRefundServices::class);
        if ($storeOrderRefundServices->count(['store_order_id' => $info['id'], 'refund_type' => [0, 1, 2, 4, 5, 6], 'is_cancel' => 0, 'is_del' => 0])) {
            return app('json')->fail('订单有售后申请请先处理',['code'=>40001]);

        }
        if ($info['pid'] == -1) return app('json')->fail('订单已被拆分为多个订单，请刷新列表数据',['code'=>40001]);

        $uid = (int)$request->uid();
        $status =$orderServices->where('order_id',$order_id)->value ('status1');
        if ($status==1.5){
            $orderServices->where('order_id',$order_id)->where('distributor_uid',$request->uid ())->update(['status1'=>3.5,'distributor_name'=>$name,'distributor_time'=>date('Y-m-d H:i:s')]);

        }
        return app('json')->success('操作完成');
    }
//===================================================
	 public function order_packing_jilu(Request $request, StoreOrder $orderServices){
         [$status1,$page, $limit] = $request->getMore([
             ['status1',1],
             ['page',1],
             ['limit',10],
         ], true);
		 $uid = (int)$request->uid();
         if ($status1==1)
             $where = 'distributor_uid';
         if ($status1==2)
             $where = 'cashier_uid';
         if ($status1==3)
             $where = 'flow_uid';

          $data = $orderServices->where($where,$request->uid ())
              ->where('refund_status','in','0,3')
              ->where('shipping_type','in','1,3')


              ->where('refund_type','in','0,3')
                ->wherein('product_type',[0,101,100])
              ->page($page, $limit)
              ->order('add_time desc')
              ->select()
              ->toArray();
		  return app('json')->success('success',$data);
	}

    /**
     * 配送订单列表
     * @param Request $request
     * @return mixed
     */
//    public function orderLists(Request $request, BranchOrderServices $orderServices)
//    {
//        [$unit_id,$status] = $request->getMore([
//            ['unit_id',2],
//            ['status',10]
//        ], true);
//
//        $uid = (int)$request->uid();
//
//        if ($status==10){
//            $where = ['unit_id' => $unit_id,  'status' => $status, 'is_del' => 0, 'is_system_del' => 0, 'paid' => 1, 'refund_status' => [0, 3]];
//            $list1 = $orderServices->getStoreOrderList2($where, ['*'], ['pink', 'store' => function ($query) {
//                $query->field('id,name,address,detailed_address');
//            }]);
//            $list2 = [];
//            foreach ($list1 as $v) {
//                $list2[$v['unit']]['date'][]=$v;
//                $list2[$v['unit']]['nuit_name']=$v['nuit_name'];
//                if (!isset($list2[$v['unit']]['time'])){
//                    $list2[$v['unit']]['time']=$v['pay_time'];
//                }else{
//                    $list2[$v['unit']]['time']=$list2[$v['unit']]['time']<$v['pay_time']?$v['pay_time']:$list2[$v['unit']]['time'];
//                }
//            }
//            $list3=[];
//            foreach ($list2 as  $v) {
//                $list3[]=$v;
//            }
//
//            $list = [];
//            $len = count($list3);
//            for ($i = 0; $i < $len - 1; $i++) {
//                for ($j = 0; $j < $len - $i - 1; $j++) {
//                    if ($list3[$j]['time'] > $list3[$j + 1]['time']) {
//                        $temp = $list3[$j];
//                        $list3[$j] = $list3[$j + 1];
//                        $list3[$j + 1] = $temp;
//                    }
//                }
//            }
//            $list = $list3;
//            $data = [];
//            $where['status'] = 2;
//            $data['unsend'] = $orderServices->count($where);
//            $where['status'] = 9;
//            $data['send'] = $orderServices->count($where);
//            return app('json')->successful(compact('data', 'list'));
//        }else{
//            $where = ['address_location' => $unit_id, 'status' => $status, 'is_del' => 0, 'is_system_del' => 0, 'paid' => 1, 'refund_status' => [0, 3]];
//            $list = $orderServices->getStoreOrderList2($where, ['*'], ['pink', 'store' => function ($query) {
//                $query->field('id,name,address,detailed_address');
//            }]);
//            $data = [];
//            $where['status'] = 2;
//            $data['unsend'] = $orderServices->count($where);
//            $where['status'] = 9;
//            $data['send'] = $orderServices->count($where);
//            return app('json')->successful(compact('data', 'list'));
//        }
//
//    }
    public function orderListss(Request $request, BranchOrderServices $orderServices)
    {
        [$unit_id,$status,$cat,$product_type] = $request->getMore([
            ['unit_id',2],
            ['status',10],
            ['cat',''],
            ['product_type',0]
        ], true);

        $uid = (int)$request->uid();
        if ($cat==2){
            $uid=$uid;
        }else{
            $uid=[0,$uid];
        }
        if ($status==10){
//				$where = ['unit_id' => $unit_id,'status' => $status, 'is_del' => 0, 'is_system_del' => 0, 'paid' => 1, 'refund_status' => [0, 3],'delivery_uid' => [0, $uid],'cat' =>$cat];
            $where = ['unit_id' => $unit_id,'status' => 10,'is_system_del' => 0, 'cat' => $cat, 'product_type' => $product_type,'delivery_uid'=> $uid];

            $list1 = $orderServices->getStoreOrderList2($where, ['*'], ['pink', 'store' => function ($query) {
                $query->field('id,name,address,detailed_address');
            }]);
            $list2 = [];
            foreach ($list1 as $v) {
                $list2[$v['unit']]['data'][]=$v;
                $list2[$v['unit']]['nuit_name']=$v['nuit_name'];

                if (!isset($list2[$v['unit']]['time'])){
                    $list2[$v['unit']]['time']=$v['pay_time'];
                }else{
                    $list2[$v['unit']]['time']=$list2[$v['unit']]['time']>$v['pay_time']?$v['pay_time']:$list2[$v['unit']]['time'];
                }
            }
            $list3=[];
            foreach ($list2 as  $v) {
                $list3[]=$v;
            }
            $list = [];
            $len = count($list3);
            for ($i = 0; $i < $len - 1; $i++) {
                for ($j = 0; $j < $len - $i - 1; $j++) {
                    if ($list3[$j]['time'] > $list3[$j + 1]['time']) {
                        $temp = $list3[$j];
                        $list3[$j] = $list3[$j + 1];
                        $list3[$j + 1] = $temp;
                    }
                }
            }
            $list = $list3;
            $data = [];
            return app('json')->successful(compact('data', 'list'));
        }elseif($status==101){
            $where = ['address_location' => $unit_id, 'status' => $status,'is_system_del' => 0, 'cat' => $cat,'product_type' => $product_type,'delivery_uid'=> $uid];
            $list = $orderServices->getStoreOrderList2($where, ['*'], ['pink', 'store' => function ($query) {
                $query->field('id,name,address,detailed_address');
            }]);
            $data = [];
            return app('json')->successful(compact('data', 'list'));
        }

    }
//水站流转员=====================================================================================================水站流转员
    public function order_list_flow1(Request $request, BranchOrderServices $orderServices)
    {


        [$status,$address_ids] = $request->getMore([
            ['status',10],
            ['address_ids',''],
        ], true);
        $datas=[];
        if ($status==10){
            $address =Db::name('user_ship_address')->where ('id',$address_ids)->order ('sort','desc')->field ('id,name')->select();
            foreach ($address as $k2 => &$v2) {
                $addresss = Db::name('user_ship_address')->where ('pid',$v2['id'])->order ('sort','desc')->field ('id,name')->select();
                foreach ($addresss as $k1 => &$v1) {
                    $addresss = Db::name('user_ship_address')->where ('pid',$v1['id'])->order ('sort','desc')->field ('id,name')->select();
                    foreach ($addresss as $k1 => &$v11) {
                        $where = ['unit_id' => $v11['id'],'status' => 1114,'is_system_del' => 0,'delivery_uid'=>0];
                        $v11['count'] =       $orderServices->getcount2($where);
                        $v11['data'] =       $orderServices->getStoreOrderList2($where, ['*']);
                        if ($v11['count']>0 ){
                            $datas[]=$v11;
                        }
                    }
                }
            }
        }elseif($status==101){
            $addresss = Db::name('user_ship_address')->wherein ('id',$address_ids)->order ('sort','desc')->field ('id,name')->select();

            foreach ($addresss as &$v1) {
                $where = ['address_location' => $v1['id'],'status' => 1114,'is_system_del' => 0,'delivery_uid'=>0];

                $v1['count'] =       $orderServices->getcount2($where);
                $v1['data'] =       $orderServices->getStoreOrderList2($where, ['*']);
                if ($v1['count']>0 ){
                    $datas[]=$v1;
                }
            }
        }

        return app('json')->successful($datas);
    }
    public function order_list_flow_count(Request $request, BranchOrderServices $orderServices)
    {


        $where = ['status' => 1111, 'is_del' => 0,'is_system_del' => 0,'delivery_uid'=>[0, $request->uid]];

        $datas['packing_count'] =  $orderServices->getcount2($where);
        $datas['flow_count']=0;
        [$status,$address_ids] = $request->getMore([
            ['status',10],
            ['address_ids',''],
        ], true);
        if ($status==10){
            $address =Db::name('user_ship_address')->where ('id',$address_ids)->order ('sort','desc')->field ('id,name')->select();
            foreach ($address as $k2 => &$v2) {
                $addresss = Db::name('user_ship_address')->where ('pid',$v2['id'])->order ('sort','desc')->field ('id,name')->select();
                foreach ($addresss as $k1 => &$v1) {
                    $addresss = Db::name('user_ship_address')->where ('pid',$v1['id'])->order ('sort','desc')->field ('id,name')->select();
                    foreach ($addresss as $k1 => &$v11) {
                        $where = ['unit_id' => $v11['id'],'status' => 1114,'is_system_del' => 0,'delivery_uid'=>0];
                        $v11['count'] =       $orderServices->getcount2($where);
                        if ($v11['count']>0 ){
                            $datas['flow_count']+=1;
                        }
                    }
                }
            }
        }elseif($status==101){
            $addresss = Db::name('user_ship_address')->wherein ('id',$address_ids)->order ('sort','desc')->field ('id,name')->select();

            foreach ($addresss as &$v1) {
                $where = ['address_location' => $v1['id'],'status' => 1114,'is_system_del' => 0,'delivery_uid'=>0];

                $v1['count'] =       $orderServices->getcount2($where);
                if ($v1['count']>0 ){
                    $datas['flow_count']+=1;
                }
            }
        }

        $count =  DB::name('store_order')->where('type',14)->where('status',2)->where('return_of_goods_processing',1)->count();

        $datas['return_count']=$count;

        return app('json')->successful($datas);
    }
    public function order_list_flow_index1(Request $request, BranchOrderServices $orderServices)
    {

        $uid = (int)$request->uid();

        [$status, $address_id] = $request->getMore([
            ['status', 10],
            ['address_id', ''],
        ], true);

        $where = ['status' => 1114,'is_system_del' => 0,'delivery_uid'=>0];
        if ($status==10){
            $where['unit_id']=$address_id;
        }elseif($status==101){
            $where['address_location']=$address_id;
        }
        $data['count'] =       $orderServices->getcount2($where);
        $data['data'] =       $orderServices->getStoreOrderList2($where, ['*']);
        return app('json')->successful($data);

    }
    public function order_ok_flow1(Request $request,BranchOrderServices $orderServices){
        // 从请求中获取订单状态和地址ID，如果未提供，则使用默认值
        [$status,$address_id,$delivery_uid] = $request->getMore([
            ['status',10],
            ['address_id',],
            ['delivery_uid',],
        ], true);

        // 根据订单状态查询符合条件的订单
        if ($status==10){
            // 如果状态为10，根据单位ID和订单状态查询订单
            $where = ['unit_id' => $address_id,'status' => 1114,'is_system_del' => 0,'delivery_uid'=>0];
        }elseif ($status==101){
            // 如果状态为101，根据地址位置和订单状态查询订单
            $where = ['address_location' =>$address_id,'status' => 1114,'is_system_del' => 0,'delivery_uid'=>0];
        }

        // 执行查询，获取订单列表
        $data=  $orderServices->getStoreOrderList22($where, ['order_id']);

        // 提取订单ID列表
        $order_id = array_column($data,'order_id');
        $order=DB::name('store_order')
            ->where('order_id','in',$order_id)
            ->where('pid','>',0)
            ->where('is_del',0)
            ->where('solve_status_refund',0)
            ->field('order_id')
            ->select()
            ->toArray();
        if (!empty($order)){
                foreach ($order as $k=>&$v){
                    $v['data']=$this->delivery_order_detail($v['order_id']);
            }
            return app('json')->success('订单有售后申请请先处理',['code'=>40001,'data'=>$order]);

        }

        // 更新订单状态和配送员信息
        $name=DB::name('delivery_service')->where('uid','in',$request->uid())->value('nickname');
        DB::name('store_order')->where('order_id','in',$order_id)
            ->update(['status1'=>4,'flow_time'=>date('Y-m-d H:i:s'),'flow_name'=>$name,'delivery_uid'=>$delivery_uid]);

        // 返回操作成功响应
        return app('json')->success('操作完成');
    }
    public function solve_status_refund1(Request $request,BranchOrderServices $orderServices){

        [$order_id] = $request->postMore([
            ['order_id',],
        ], true);
        foreach (explode(',',$order_id) as $k=>&$v){

        $order =Db::name('store_order')->where('order_id',$v)->find();
        $name='流转员已处理';
        if ($order['set_type']==2||$order['product_type']==100){
            $name='流转员已处理';
        }
            Db::name('store_order')->where('order_id',$v)->update(['solve_status_refund'=>1,'solve_status_title'=>$name,'solve_status_refund_img'=>'']);
        }

        return app('json')->success('处理完成');
    }
//退货专区
    public function refund_list(Request $request,BranchOrderServices $orderServices){

        [$page,$limit] = $request->postMore([
            ['$page',1],
            ['limit',10],
        ], true);

        $data =  DB::name('store_order')->page($page,$limit)->where('type',14)->where('status',2)->where('return_of_goods_processing',1)->select()->toArray();

        return app('json')->successful($data);

    }
    public function refund_goods_num(request $request)
    {
        [$data] = $request->postMore([
            ['data',[]],
        ], true);
        try {
            DB::startTrans();
            foreach ($data as $k=>$v){
                $product_attr_value= Db::name('store_product_attr_value')->where('unique',$v['unique'])->find();
                if ($v['warehousing_num']>0){
                    if ($product_attr_value){
                        $stock='stock';
                        if ($product_attr_value['type']==1) {
                            $stock = 'quota';
                            Db::name('store_product_attr_value')->where('unique',$v['unique'])->inc($stock,$v['warehousing_num'])->update();
                            DB::name('store_seckill')->where('id', $product_attr_value['product_id'])->inc($stock, $v['warehousing_num'])->update();
                        }
                        if ($product_attr_value['type']==4){
                            DB::name('store_product_attr_value')->where('id', $product_attr_value['product_id'])->inc($stock, $v['warehousing_num'])->update();
                            Db::name('store_integral')->where('unique',$v['unique'])->inc($stock,$v['warehousing_num'])->update();
                        }
                        $datas = ['goods_name'=>$v['goods_name'],
                            'nums'=>$v['warehousing_num'],
                            'reason'=>$v['waste_reason'],
                            'type'=>1,
                            'order_id'=>$v['order_id'],
                            'img'=>$v['warehousing_img'],
                            'u_id'=>$request->uid(),
                            'goods_id'=>$v['goods_id'],
                            'suk'=>$product_attr_value['suk'],
                            'add_time'=>date('Y-m-d H:i:s'),
                            'goods_img'=>$v['goods_img']];
                        Db::name('recovery_goods_list')->insert($datas);
                    }else{
                        $datas = ['goods_name'=>$v['goods_name'],
                            'nums'=>$v['warehousing_num'],
                            'type'=>2,
                            'reason'=>$v['waste_reason'],
                            'order_id'=>$v['order_id'],
                            'img'=>$v['warehousing_img'],
                            'u_id'=>$request->uid(),
                            'goods_id'=>$v['goods_id'],
                            'add_time'=>date('Y-m-d H:i:s'),
                            'suk'=>$product_attr_value['suk'],
                            'goods_img'=>$v['goods_img']];

                        Db::name('recovery_goods_list')->insert($datas);
                    }
                }
                if ($v['waste_num']>0){
                    $datas = ['goods_name'=>$v['goods_name'],
                        'nums'=>$v['waste_num'],
                        'type'=>2,
                        'order_id'=>$v['order_id'],
                        'img'=>$v['waste_img'],
                        'reason'=>$v['waste_reason'],
                        'u_id'=>$request->uid(),
                        'goods_id'=>$v['goods_id'],
                        'suk'=>$product_attr_value['suk'],
                        'add_time'=>date('Y-m-d H:i:s'),
                        'suk'=>date('Y-m-d H:i:s'),
                        'goods_img'=>$v['goods_img']];
                    Db::name('recovery_goods_list')->insert($datas);

                }
            }
            Db::name('store_order')->where('order_id',$data[0]['order_id'])->update(['return_of_goods_processing'=>2]);
            Db::commit();
            return app('json')->successful('处理成功');
        }catch (\Throwable $e){
            Db::rollback();
            return app('json')->fill('失败，原因：' . $e->getMessage());
        }

    }

    //退货纪律

    public function get_recovery_goods_list(Request $request)
    {
        [$page, $limit, $type, $time] = $request->postMore([
            ['$page', 1],
            ['limit', 10],
            ['type', 1],
            ['time', 1],
        ], true);
        $data = Db::name('recovery_goods_list')
            ->alias('r')->join('store_order o','o.order_id = r.order_id')
            ->where('r.type',$type)
            ->whereMonth('r.add_time',$time)
            ->page($page, $limit)
            ->field('r.*,o.user_address,o.user_location,o.confirm_time,o.real_name'
            )->select()
            ->toArray();
        return app('json')->successful('成功',$data);
    }

    /**
     * 流转员流转完成处理逻辑
     *
     * 该方法根据请求参数获取订单状态和地址ID，然后根据这些参数查询符合条件的订单，
     * 并更新这些订单的状态和配送员信息
     *
     * @param Request $request 用户请求对象，包含订单状态和地址ID等信息
     * @param BranchOrderServices $orderServices 订单服务对象，用于执行订单相关的操作
     *
     * @return \think\response\Json 操作成功后的JSON响应
     */
//流转员======================================================================================================
    /**
     * 流转员选择站点列表
     * @param Request $request
     * @return mixed
     */
    public function flow_address(Request $request, BranchOrderServices $orderServices)
    {
        [$status] = $request->postMore([
            ['status',10],
        ], true);
        $data=Db::name('user_ship_address')->where ('pid', 0)->field ('id,name,station_type')->order ('sort','desc')->select();
        $address = [];
        foreach ($data as $k=>&$v) {

                if ($status==10){
                    if ($v['station_type']==1) {
                        $address[] = $v;
                    }
                }else{
                    if ($v['id']!=1) {
                        $address[] = $v;
                    }
                }
        }
        return app('json')->successful('ok',$address);

    }
    /**
     * 流转员没有接单订单列表
     * @param Request $request
     * @return mixed
     */
    public function order_list_flow(Request $request, BranchOrderServices $orderServices)
    {


        [$status,$address_ids] = $request->getMore([
            ['status',10],
            ['address_ids',''],
        ], true);
        $datas=[];
        if ($status==10){
            $address =Db::name('user_ship_address')->where ('id',$address_ids)->order ('sort','desc')->field ('id,name')->select();
            foreach ($address as $k2 => &$v2) {
                $addresss = Db::name('user_ship_address')->where ('pid',$v2['id'])->order ('sort','desc')->field ('id,name')->select();
                foreach ($addresss as $k1 => &$v1) {
                    $addresss = Db::name('user_ship_address')->where ('pid',$v1['id'])->order ('sort','desc')->field ('id,name')->select();
                    foreach ($addresss as $k1 => &$v11) {
                        $where = ['unit_id' => $v11['id'],'status' => 113,'is_system_del' => 0,'delivery_uid'=>0];
                        $v11['count'] =       $orderServices->getcount2($where);
                        if ($v11['count']>0 ){
                            $v11['data'] =       $orderServices->getStoreOrderList2($where, ['*']);
                            $datas[]=$v11;
                        }
                    }
                }
            }
        }elseif($status==101){
            $addresss = Db::name('user_ship_address')->wherein ('id',$address_ids)->order ('sort','desc')->field ('id,name')->select();

            foreach ($addresss as &$v1) {
                $where = ['address_location' => $v1['id'],'status' => 113,'is_system_del' => 0,'delivery_uid'=>0];

                $v1['count'] =       $orderServices->getcount2($where);
                if ($v1['count']>0 ){
                    $v1['data'] =       $orderServices->getStoreOrderList2($where, ['*']);
                    $datas[]=$v1;
                }
            }
        }

        return app('json')->successful($datas);
    }
    public function order_list_flow_index(Request $request, BranchOrderServices $orderServices)
    {

        $uid = (int)$request->uid();

        [$status, $address_id] = $request->getMore([
            ['status', 10],
            ['address_id', ''],
        ], true);

        $where = ['status' => 113,'is_system_del' => 0,'delivery_uid'=>0];
        if ($status==10){
            $where['unit_id']=$address_id;
        }elseif($status==101){
            $where['address_location']=$address_id;
        }
        $data['count'] =       $orderServices->getcount2($where);
        $data['data'] =       $orderServices->getStoreOrderList2($where, ['*']);
        return app('json')->successful($data);

    }
    public function order_judge_correct(Request $request)
    {
        [$count,$oid] = $request->getMore([
            ['count',0],
            ['oid',''],
        ], true);

        $cart_num=StoreOrderCartInfo::where(['oid'=>$oid])->sum('cart_num');
        if (Db::name('store_order')->where ('id',$oid)->where('pid',-1)->find()){
            return app('json')->fail('订单数量有误,请刷新订单');
        }
        if ($cart_num!=$count){
            return app('json')->fail('订单数量有误,请刷新订单');
        }
        return app('json')->success('验证成功');
    }
    /**
     * 流转员接单后配送订单列表
     * @param Request $request
     * @return mixed
     */
    public function order_ok_flow_list(Request $request, BranchOrderServices $orderServices)
    {

        $uid = (int)$request->uid();
        [$status,$address_ids] = $request->getMore([
            ['status',10],
            ['address_ids',''],
        ], true);
        $datas=[];
        if ($status==10){
            $address =Db::name('user_ship_address')->where ('id',$address_ids)->order ('sort','desc')->field ('id,name')->select();
            foreach ($address as $k2 => &$v2) {
                $addresss = Db::name('user_ship_address')->where ('pid',$v2['id'])->order ('sort','desc')->field ('id,name')->select();
                foreach ($addresss as $k1 => &$v1) {
                    $addresss = Db::name('user_ship_address')->where ('pid',$v1['id'])->order ('sort','desc')->field ('id,name')->select();
                    foreach ($addresss as $k11 => &$v3){
                        $where = ['unit_id' => $v3['id'],'status' => 114,'is_system_del' => 0,'delivery_uid'=>$uid];

                        $v3['count'] =       $orderServices->getcount2($where);
                        $v3['data'] =       $orderServices->getStoreOrderList2($where, ['*']);
                        if ($v3['count']>0 ){
                            $datas[]=$v3;
                        }
                    }
                }
            }
        }elseif($status==101){
            $addresss = Db::name('user_ship_address')->wherein ('id',$address_ids)->order ('sort','desc')->field ('id,name')->select();

            foreach ($addresss as &$v1) {
                $where = ['address_location' => $v1['id'],'status' => 114,'is_system_del' => 0,'delivery_uid'=>$uid];
                $v1['count'] =       $orderServices->getcount2($where);
                $v1['data'] =       $orderServices->getStoreOrderList2($where, ['*']);
                if ($v1['count']>0 ){
                    $datas[]=$v1;
                }
            }
        }

        return app('json')->successful($datas);
    }
    public function order_flow_list_count(Request $request, BranchOrderServices $orderServices)
    {

        $uid = (int)$request->uid();
        [$status,$address_ids] = $request->getMore([
            ['status',10],
            ['address_ids',''],
        ], true);
        $datas=['count_no'=>0,'count_ok'=>0,];
        if ($status==10){
            $address =Db::name('user_ship_address')->where ('id',$address_ids)->order ('sort','desc')->field ('id,name')->select();
            foreach ($address as $k2 => &$v2) {
                $addresss = Db::name('user_ship_address')->where ('pid',$v2['id'])->order ('sort','desc')->field ('id,name')->select();
                foreach ($addresss as $k1 => &$v1) {
                    $addresss = Db::name('user_ship_address')->where ('pid',$v1['id'])->order ('sort','desc')->field ('id,name')->select();
                        foreach ($addresss as $k11 => &$v3){

                            $v3['count_no'] =       $orderServices->getcount2(['unit_id' => $v3['id'],'status' => 113,'is_system_del' => 0,'delivery_uid'=>0]);
                            $v3['count_ok'] =       $orderServices->getcount2(['unit_id' => $v3['id'],'status' => 114,'is_system_del' => 0,'delivery_uid'=>$uid]);
                            if ($v3['count_no']>0){
                                $datas['count_no']+=1;
                            }
                            if ($v3['count_ok']>0){
                                $datas['count_ok']+=1;
                            }

                        }
                }
            }
        }elseif($status==101){
            $addresss = Db::name('user_ship_address')->wherein ('id',$address_ids)->order ('sort','desc')->field ('id,name')->select();

            foreach ($addresss as &$v1) {
                $v1['count_no'] =       $orderServices->getcount2(['address_location' =>  $v1['id'],'status' => 113,'is_system_del' => 0,'delivery_uid'=>0]);
                $v1['count_ok'] =       $orderServices->getcount2(['address_location' => $v1['id'],'status' => 114,'is_system_del' => 0,'delivery_uid'=>$uid]);
                if ($v1['count_no']){
                    $datas['count_no']+=1;
                }
                if ($v1['count_ok']){
                    $datas['count_ok']+=1;
                }
            }
        }

        return app('json')->successful($datas);
    }
    /**
     * 流转员接单流程
     *
     * 该方法根据请求参数获取订单状态和地址ID，然后根据这些参数查询符合条件的订单，
     * 并更新这些订单的状态和配送员信息
     *
     * @param Request $request 用户请求对象，包含订单状态和地址ID等信息
     * @param BranchOrderServices $orderServices 订单服务对象，用于执行订单相关的操作
     *
     * @return \think\response\Json 操作成功后的JSON响应
     */
    public function order_add_flow(Request $request,BranchOrderServices $orderServices){
        // 从请求中获取订单状态和地址ID，如果未提供，则使用默认值
        [$status,$address_id] = $request->getMore([
            ['status',10],
            ['address_id',],
        ], true);

        // 根据订单状态查询符合条件的订单
        if ($status==10){
            // 如果状态为10，根据单位ID和订单状态查询订单
            $where = ['unit_id' => $address_id,'status' => 113.5,'is_system_del' => 0,'delivery_uid'=>0];
        }elseif ($status==101){
            // 如果状态为101，根据地址位置和订单状态查询订单
            $where = ['address_location' =>$address_id,'status' => 113,'is_system_del' => 0,'delivery_uid'=>0];
        }

        // 执行查询，获取订单列表
        $data=  $orderServices->getStoreOrderList22($where, ['order_id']);
        // 提取订单ID列表
        $order_id = array_column($data,'order_id');
        // 更新订单状态和配送员信息
        DB::name('store_order')->where('order_id','in',$order_id)->update(['status1'=>3.5,'flow_uid'=>$request->uid ()]);

        // 返回操作成功响应
        return app('json')->success('操作完成');
    }
    /**
     * 流转员流转完成处理逻辑
     *
     * 该方法根据请求参数获取订单状态和地址ID，然后根据这些参数查询符合条件的订单，
     * 并更新这些订单的状态和配送员信息
     *
     * @param Request $request 用户请求对象，包含订单状态和地址ID等信息
     * @param BranchOrderServices $orderServices 订单服务对象，用于执行订单相关的操作
     *
     * @return \think\response\Json 操作成功后的JSON响应
     */
    public function order_ok_flows(Request $request,BranchOrderServices $orderServices){
        // 从请求中获取订单状态和地址ID，如果未提供，则使用默认值
        [$status,$address_id,$delivery_uid] = $request->getMore([
            ['status',10],
            ['address_id',],
            ['delivery_uid',],
        ], true);

        // 根据订单状态查询符合条件的订单
        if ($status==10){
            // 如果状态为10，根据单位ID和订单状态查询订单
            $where = ['unit_id' => $address_id,'status' => 114,'is_system_del' => 0,'delivery_uid'=>$request->uid ()];
        }elseif ($status==101){
            // 如果状态为101，根据地址位置和订单状态查询订单
            $where = ['address_location' =>$address_id,'status' => 114,'is_system_del' => 0,'delivery_uid'=>$request->uid ()];
        }

        // 执行查询，获取订单列表
        $data=  $orderServices->getStoreOrderList22($where, ['order_id']);

        // 提取订单ID列表
        $order_id = array_column($data,'order_id');

        // 更新订单状态和配送员信息
        $name=DB::name('delivery_service')->where('uid','in',$request->uid())->value('nickname');
        DB::name('store_order')->where('order_id','in',$order_id)
            ->where('flow_uid',$request->uid ())
            ->update(['status1'=>4,'flow_time'=>date('Y-m-d H:i:s'),'flow_name'=>$name,'delivery_uid'=>$delivery_uid]);

        // 返回操作成功响应
        return app('json')->success('操作完成');
    }
    //===========================================================================================
    //楼盘楼盘楼盘楼盘楼盘楼盘楼盘楼盘楼盘楼盘楼盘楼盘楼盘楼盘楼盘
    public function delivery_building_save(Request $request,BranchOrderServices $orderServices){
        [$unit,$type] = $request->postMore([
            ['unit',''],
            ['type',''],
        ], true);

        $unit=json_decode($unit,true);

        Db::name('unit_con')->where('delivery_id',$request->uid())->where('type',$type)->delete();
        if (empty($unit)){
            return app('json')->success('操作完成');
        }
        foreach ($unit as $k=>$v){
            Db::name('unit_con')->insert([
                'unit_id'=>$v['unit_id'],
                'name'=>$v['name'],
                'type'=>$type,
                'delivery_id'=>$request->uid(),
            ]);
        }
        return app('json')->success('操作完成');
    }
    //流转员查询此楼盘的配送员
    public function delivery_building_list(Request $request,BranchOrderServices $orderServices){
        [$unit_id] = $request->postMore([
            ['unit_id',''],
        ], true);
        $delivery_info = [];
        $data =Db::name('unit_con')->where('unit_id',$unit_id)->group('delivery_id')->select()->toArray();

        foreach ($data as $v){
            $delivery_info[]=Db::name('delivery_service')->where('uid',$v['delivery_id'])->find();
        }

        return app('json')->successful($delivery_info);
    }
    public function delivery_user_list(Request $request,BranchOrderServices $orderServices){
        [$type] = $request->postMore([
            ['type',''],
        ], true);
        $data =Db::name('unit_con')->where('delivery_id',$request->uid())->where('type',$type)->select()->toArray();

        return app('json')->successful($data);
    }
    public function solve_status_refund(Request $request,BranchOrderServices $orderServices){

        [$solve_status_refund_img,$order_id] = $request->postMore([
            ['solve_status_refund_img',''],
            ['order_id',],
        ], true);
        $order = Db::name('store_order')->where('order_id',$order_id)->find();

        $name='';
        if ($order['set_type']==2){
            $name='配送员已处理';
            if ($order['status1']==1.5){
                $name='配货员已处理';
            }elseif ($order['status1']>=2&&$order['status1']<=3.5){
                $name='收银员已处理';
            }elseif ($order['status1']==4){
                $name='配送员已处理';
            }

        }elseif ($order['set_type']==1){
            $name='配货员已处理';
            if ($order['status1']==1.5){
                $name='配货员已处理';
            }elseif ($order['status1']>=2&&$order['status1']<3.5){
                $name='收银员已处理';
            }elseif ($order['status1']==3.5){
                $name='流转员已处理';
            }elseif ($order['status1']==4){
                $name='配送员已处理';
            }
        }
        Db::name('store_order')->where('order_id',$order_id)->update(['solve_status_refund'=>1,'solve_status_title'=>$name,'solve_status_refund_img'=>$solve_status_refund_img]);

        return app('json')->success('处理完成');
    }
    //            $data=[];
//
//            if ($item['pid']>0){
//                $order = DB::name('store_order')->where(['pid'=>$item['pid'],'refund_status'=>2])->field('id')->select();
//                foreach ($order as $v){
//                    $store_order_cart_info =$servicessss->getOrderCartInfo((int)$v['id']);
//
//                    foreach ($store_order_cart_info as $vv){
//                            if (!isset($data[$vv['cart_info']['product_id']]['refund_nums'])){
//                                $data[$vv['cart_info']['product_id']]['refund_nums']=0;
//                            }
//                       $data[$vv['cart_info']['product_id']]['refund_nums'] += $vv['cart_info']['refund_num'];
//                       $data[$vv['cart_info']['product_id']]['cart_info'] = $vv['cart_info'];
//                   }
//                }
//            }
    /*    $status=false;
            foreach ($data as $k=>$vs){
                if ($items['cart_info']['product_id'] == $k){
                    $items['cart_info']['refund_num'] = $vs['refund_nums'];
                    $items['cart_info']['cart_num'] += $vs['cart_info']['cart_num'];
                    unset ($data[$k]);
                    $status=true;
                }
            }
            if (!$status){
                $items['cart_info']['refund_num'] = 0;
            }

    if (count($data)>0){
        foreach ( $data as $k=>$vs){
            $item['_info'][$vs['cart_info']['id']]['cart_info']  = $vs['cart_info'];
        }
    }*/
    public function delivery_order_detail($uni)
    {
            /** @var StoreOrderWapServices $services*/
        $services = app()->make(StoreOrderWapServices::class);
        /** @var StoreOrderRefundServices $StoreOrderRefundServices $services*/
        $StoreOrderRefundServices = app()->make(StoreOrderRefundServices::class);



        $order = $services->getUserOrderDetail($uni, 0, ['invoice', 'refund' => function ($query) {
            $query->field('id,store_order_id,refunded_price,refund_explain');
        }]);

        $order = $order->toArray();
        $order['number_diners'] = 0;
        $order['serial_number'] = '';
        if ($order['type'] == 10) {
            /** @var UserCollageCodeServices $userCollageCodeServices */
            $userCollageCodeServices = app()->make(UserCollageCodeServices::class);
            $table = $userCollageCodeServices->getOne(['oid' => $order['id']], 'id,oid,number_diners,serial_number');
            if ($table) {
                $order['number_diners'] = $table['number_diners'];
                $order['serial_number'] = $table['number_diners'];
            }
        }
        $order['split'] = [];
        //门店是否开启 ｜｜ 门店核销是否开启
        if (!sys_config('store_func_status', 1) || !sys_config('store_self_mention')) {
            //关闭门店核销后 订单隐藏门店信息
            $order['shipping_type'] = 1;
        }
        /** @var StoreOrderServices $orderServices */
        $orderServices = app()->make(StoreOrderServices::class);
        $orderData = $orderServices->tidyOrder($order, true, true);
        //核算优惠金额

        if (!$orderData['cartInfo']) {
            $cartGroup = $orderServices->getCacheOrderInfo((int)$order['uid'], $order['unique']);
            $orderData['cartInfo'] = $cartGroup['cartInfo'] ?? [];
        }
        if ($orderData['type']==11){
            $orderData['water_ticket'] = Db::name('water_ticket')->where ('order_sn',$orderData['order_id'])->find ();
        }
        $orderData['water_user']  = Db::name('water_user')->where('uid',$order['uid'])->find();
        if ($orderData['pid']>0){
            $orderData['water_user_kt_list'] = DB::name('water_user_kt_list')->where('order_id',$orderData['order_id'])->find();

        }else{
            $orderData['water_user_kt_list'] = DB::name('water_user_kt_list')->where('order_id',$orderData['order_id'])->find();

        }

        if ($orderData['type']==13||$orderData['type']==14||$orderData['type']==12) {
            $orderData['refund_cartInfo'] = $StoreOrderRefundServices->refundDetail($orderData['refund_id']);

        }

        ////////////////////////////////////////////////////////
        $data=[];
        /** @var StoreOrderCartInfoServices $services */
        $servicessss = app()->make(StoreOrderCartInfoServices::class);
        if ($orderData['pid']>0){
            $order = DB::name('store_order')->where(['pid'=>$orderData['pid'],'refund_status'=>2])->field('id')->select();
            foreach ($order as $v){
                $store_order_cart_info =$servicessss->getOrderCartInfo((int)$v['id']);

                foreach ($store_order_cart_info as $vv){
                    if (!isset($data[$vv['cart_info']['product_attr_unique']]['refund_nums'])){
                        $data[$vv['cart_info']['product_attr_unique']]['refund_nums']=0;
                    }
                    if (!isset($data[$vv['cart_info']['product_attr_unique']]['cart_num'])){
                        $data[$vv['cart_info']['product_attr_unique']]['cart_num']=0;
                    }
                    $data[$vv['cart_info']['product_attr_unique']]['refund_nums'] += $vv['cart_info']['refund_num'];
                    $data[$vv['cart_info']['product_attr_unique']]['cart_num'] += $vv['cart_info']['cart_num'];

                    $data[$vv['cart_info']['product_attr_unique']]['cart_info'] = $vv['cart_info'];
                }
            }
        }
        foreach ($orderData['cartInfo'] as &$items){
            $status=false;
            foreach ($data as $k=>$vs){
                if ($items['product_attr_unique'] == $k){
                    $items['refund_num'] += $vs['refund_nums'];
                    $items['cart_num'] += $vs['cart_num'];
                    unset ($data[$k]);
                    $status=true;
                }
            }

            if ($status==false){
                $items['refund_num'] = 0;
            }

        }
        if (count($data)>0){
            foreach ( $data as $k=>$vs){
                $vs['cart_info']['cart_num']=$vs['cart_num'];
                $vs['cart_info']['refund_num']=$vs['refund_nums'];
                $orderData['cartInfo'][] = $vs['cart_info'];
            }
        }
        return $orderData;
    }




}
